import pandas as pd
from scipy.stats import spearmanr
import matplotlib.pyplot as plt
import numpy as np
# 示例数据
data = {
    'Defective Rate': [27.1, 48.8, 27.1, 48.8, 35.2, 14.3],
    'Cost': [28.1, 29.2, 30.5, 36, 29.5, 26.5]
}

df = pd.DataFrame(data)

# 计算Spearman相关系数
spearman_corr, p_value = spearmanr(df['Defective Rate'], df['Cost'])

print(f'Spearman: {spearman_corr}')
print(f'P: {p_value}')

# 可视化
plt.figure(figsize=(8, 6))
plt.scatter(df['Defective Rate'], df['Cost'], color='blue', label='data')
plt.title('Defective Rate vs Cost')
plt.xlabel('Defective Rate (%)')
plt.ylabel('Cost ($)')
plt.grid(True)

# 绘制趋势线
m, b = np.polyfit(df['Defective Rate'], df['Cost'], 1)  # 线性拟合
plt.plot(df['Defective Rate'], m * df['Defective Rate'] + b, color='red', label='trendline')

plt.legend()
plt.show()
